package com.example.ai.tool;

import com.example.ai.output.NLReq;
import io.modelcontextprotocol.client.McpSyncClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.converter.MapOutputConverter;
import org.springframework.ai.converter.StructuredOutputConverter;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.mcp.AsyncMcpToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.ai.tool.StaticToolCallbackProvider;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/tools")
public class ToolController {

    @Autowired
    private ChatModel chatModel;

    /**
     * 所有tool，包括所有ToolCallbackProvider子类的tool:
     * @see MethodToolCallbackProvider
     * @see SyncMcpToolCallbackProvider
     * @see AsyncMcpToolCallbackProvider
     * @see StaticToolCallbackProvider
     */
    @Autowired
    List<ToolCallbackProvider> toolCallbackProviders;

    @PostMapping("/invoke")
    public ResponseEntity<?> client(@RequestBody NLReq req) {
        ChatClient chatClient = ChatClient.builder(chatModel)
                .defaultAdvisors(new SimpleLoggerAdvisor())
                .defaultTools(toolCallbackProviders.toArray(new ToolCallbackProvider[0]))
                .build();
        MapOutputConverter mapOutputConverter = new MapOutputConverter();
        ChatResponse response = chatClient.prompt()
                .user(req.getContent())
                .call()
                .chatResponse();

        log.info("response:{}", response);
        return  ResponseEntity.ok(response.getResult().getOutput().getText());
    }

    record FileInfo(String fileName, String filePath){}
}
